package com.sly.demoim.service;

import cn.hutool.json.JSONUtil;
import com.sly.demoim.constant.DelStatus;
import com.sly.demoim.constant.MessageReadStatus;
import com.sly.demoim.constant.MessageSaveStatus;
import com.sly.demoim.controller.ChatWebSocket;
import com.sly.demoim.helper.ChatWebSocketHelper;
import com.sly.demoim.mapper.MessageMapper;
import com.sly.demoim.model.message.ChatMessage;
import com.sly.demoim.model.message.Message;
import com.sly.demoim.result.BaseResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 消息service
 *
 * @author SLY
 * @date 2022/7/24
 */
@Service
public class MessageService {

    @Resource
    private MessageMapper messageMapper;

    /**
     * 发送聊天消息
     *
     * @param message 消息对象
     * @return {@link BaseResult}
     * @author SLY
     * @date 2022/7/24
     */
    public BaseResult<?> sendChatMessage(ChatMessage<?> message) {
        ChatWebSocket webSocket = ChatWebSocketHelper.SOCKETS.get(message.getToUser());
        webSocket.sendMessage(message);
        return BaseResult.success();
    }

    /**
     * 保存聊天消息
     *
     * @param chatMessage 消息对象
     * @return {@link BaseResult}
     * @author SLY
     * @date 2022/7/24
     */
    public BaseResult<Message> saveMessage(ChatMessage<?> chatMessage) {
        Message message = new Message();
        message.setFromUser(chatMessage.getFromUser());
        message.setToUser(chatMessage.getToUser());
        message.setMessageType(chatMessage.getMessageType());
        message.setShowType(chatMessage.getShowType());
        message.setContent(JSONUtil.toJsonStr(chatMessage.getContent()));
        message.setUuid(chatMessage.getUuid());
        message.setCreateTime(new Date());
        message.setReadStatus(MessageReadStatus.READ.getCode());
        message.setDelStatus(DelStatus.N);
        messageMapper.insert(message);
        return BaseResult.success(message);
    }
}
